package com.one.efaimaly.main.presenter;

import android.content.Context;

import com.one.common.model.http.callback.ObserverOnResultListener;
import com.one.common.presenter.BaseApiPresenter;
import com.one.common.utils.MyToast;
import com.one.common.utils.StringUtils;
import com.one.common.utils.Toaster;
import com.one.common.utils.list.ListUtils;
import com.one.efaimaly.utils.LocationUtils;
import com.one.common.utils.pinyin.CharacterParser;
import com.one.common.utils.pinyin.PinyinComparator;
import com.one.common.view.base.BaseActivity;
import com.one.common.view.base.IListView;
import com.one.efaimaly.R;
import com.one.common.model.bean.CityBean;
import com.one.efaimaly.main.model.item.PingyinItem;
import com.one.common.common.user.modle.UserInfoModel;
import com.tencent.map.geolocation.TencentLocation;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * author ：zhulunjun
 * email  ：zhulunjun@qq.com
 * date   ：2018/8/5 下午8:26
 * description ： 选择城市
 **/
public class SelectCityPresenter extends BaseApiPresenter<IListView, UserInfoModel> implements LocationUtils.OnLocationListener {

    private CharacterParser characterParser;
    private PinyinComparator pinyinComparator;
    /**
     * 省市区中的市
     */
    private List<CityBean> cityList = new ArrayList<>();

    /**
     * 当前城市
     */
    private CityBean curCity;
    private boolean isSearch = false;
    private List<Object> cityData = new ArrayList<>();

    public SelectCityPresenter(IListView mView, Context mContext) {
        super(mView, mContext, new UserInfoModel((BaseActivity) mContext));
        characterParser = new CharacterParser();
        pinyinComparator = new PinyinComparator();

    }

    /**
     * 获取城市
     */
    public void getCitys() {
        mModel.getCitys(new ObserverOnResultListener<ArrayList<CityBean>>() {
            @Override
            public void onResult(ArrayList<CityBean> cityBeans) {
                if (!ListUtils.isEmpty(cityBeans)) {
                    handleCity(cityBeans);
                }
            }
        });
    }


    /**
     * 获取二级市
     */
    private void handleCity(List<CityBean> cityBeans) {
        for (CityBean bean : cityBeans) {
            if (!ListUtils.isEmpty(bean.getCityBeans())) {
                for (CityBean bean1 : bean.getCityBeans()) {
                    cityList.add(bean1);
                }
            }
        }
        filledData(cityList);
        location();
    }

    /**
     * 定位
     */
    public void location() {
        LocationUtils.location(mContext, this);
    }

    /**
     * 处理拼音数据
     * 并添加到页面
     */
    public static final String CUR_CITY = "cur";
    private void handlePingyin(List<CityBean> data) {
        List<Object> viewData = new ArrayList<>();
        if (curCity != null && !isSearch) {
            viewData.add(new PingyinItem("当前定位城市"));
            // 为了显示重新定位的视图
            curCity.setFirst_pingyin(CUR_CITY);
            viewData.add(curCity);
        }
        for (int i = 0; i < data.size(); i++) {
            if (!data.get(i).getFirst_pingyin().equals(CUR_CITY)) {
                if (i == 0) {
                    viewData.add(new PingyinItem(data.get(i).getFirst_pingyin()));
                } else {
                    int before;
                    if(data.get(i - 1).getFirst_pingyin().equals(CUR_CITY)) {
                        before = data.get(i - 2).getFirst_pingyin().toUpperCase().charAt(0);
                    } else {
                        before = data.get(i - 1).getFirst_pingyin().toUpperCase().charAt(0);
                    }
                    int current = data.get(i).getFirst_pingyin().toUpperCase().charAt(0);
                    if (before != current) {
                        viewData.add(new PingyinItem(data.get(i).getFirst_pingyin()));
                    }
                }
                viewData.add(data.get(i));
            }
        }

        if (ListUtils.isEmpty(mView.getData())) {
            cityData.addAll(viewData);
            mView.loadSuccess(viewData);
        } else {
            mView.replaceData(viewData);
        }
    }

    public void defaultData() {
        isSearch = false;
        mView.replaceData(cityData);
    }

    /**
     * 获取名字首字母-大写
     * 加工数据
     */
    private List<CityBean> filledData(List<CityBean> data) {
        for (CityBean cityBean : data) {
            String pinyin = characterParser.getSelling(cityBean.getName());
            String sortString = pinyin.substring(0, 1).toUpperCase();

            if (sortString.matches("[A-Z]")) {
                cityBean.setFirst_pingyin(sortString.toUpperCase());
            } else {
                cityBean.setFirst_pingyin("#");
            }
        }

        //根据首字母排序
        Collections.sort(data, pinyinComparator);
        return data;

    }

    /**
     * 根据输入框中的值来过滤数据并更新数据
     *
     * @param filterStr
     */
    public List<CityBean> filterData(String filterStr) {
        List<CityBean> filterDateList = new ArrayList<>();

        if (StringUtils.isEmpty(filterStr)) {
            filterDateList = cityList;
        } else {
            filterDateList.clear();
            for (CityBean sortModel : cityList) {
                String name = sortModel.getName();
                // 拼音匹配，汉字匹配
                if (name.toUpperCase().indexOf(filterStr.toString().toUpperCase()) != -1
                        || characterParser.getSelling(name).toUpperCase()
                        .startsWith(filterStr.toString().toUpperCase())) {
                    filterDateList.add(sortModel);
                }
            }
        }

        // 根据a-z进行排序
        Collections.sort(filterDateList, pinyinComparator);
        isSearch = true;
        filledData(filterDateList);
        handlePingyin(filterDateList);
        return filterDateList;
    }

    private void locationCity(String city) {
        for (CityBean bean : cityList) {
            if (bean.getName().equals(city)) {
                curCity = bean;
            }
        }
        if (mView != null) {
            if (!ListUtils.isEmpty(mView.getData())) {
                // 重新定位
                CityBean bean = (CityBean) mView.getData().get(1);
                bean.setName(curCity.getName());
                mView.getAdapter().notifyItemChanged(1);
            } else {
                // 第一次定位
                handlePingyin(cityList);
            }
        }

    }


    @Override
    public void onLocated(TencentLocation aMapLocation) {
        if (aMapLocation != null) {
            locationCity(aMapLocation.getCity());
        }
    }

    @Override
    public void onLocationPermissionFail() {
        Toaster.showLongToast(StringUtils.format(R.string.permission_fail_local), MyToast.FAIL);
        handlePingyin(cityList);
    }
}
